import {createRouter, createWebHashHistory, RouteRecordRaw} from 'vue-router'
import store from '@/store/store'

const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        name: 'Login',
        component: () => import('../views/index/Login.vue'),
        meta: {
            title: '登录界面'
        }
    },
    {
        path: '/login',
        redirect: '/'
    },
    // {
    //     path: '/index',
    //     name: 'Index',
    //     component: () => import('../views/index/index.vue'),
    //     meta: {
    //         title: '大屏界面'
    //     }
    // },
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

// Function to add routes dynamically
function addDynamicRoutes() {
    const dynamicRoutes: Array<RouteRecordRaw> = [
        {
            path: '/index',
            name: 'Index',
            component: () => import('../views/index/index.vue'),
            meta: {
                title: '大屏界面',
                requiresAuth: true  // 添加此属性来指示此路由需要鉴权
            }
        }
        // You can add more dynamic routes here...
    ]

    dynamicRoutes.forEach(route => {
        router.addRoute(route)
    })
}


function isLoggedIn() {
    const loggedIn = store.getters['isLoggedIn/isUserLoggedIn'];
    return loggedIn;
}

router.beforeEach((to, from, next) => {
    const pageTitle = to.meta.title || 'Default Title'
    document.title = pageTitle as string

    if (to.matched.some(record => record.meta.requiresAuth) && !isLoggedIn()) {
        // 如果路由需要鉴权，并且用户未登录，那么重定向到登录页面
        next({
            path: '/login',
            // 保存我们所在的位置，以便在登录后返回
            query: {redirect: to.fullPath}
        });
    } else if (to.path === '/' && isLoggedIn()) { // 检查是否用户尝试访问登录页面且已经登录
        next('/Index'); // 或其他你想重定向的页面
    } else {
        next();
    }
})

addDynamicRoutes()

export default router
